package com.mama100.rpc.mdp.spring;

import java.net.InetSocketAddress;

import java.util.List;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.mama100.common.finagle.util.NetUtil;
import com.twitter.common.quantity.Amount;
import com.twitter.common.quantity.Time;
import com.twitter.common.zookeeper.ZooKeeperClient;

public class ZkClientFactoryBean implements FactoryBean<ZooKeeperClient>, InitializingBean {

	private String zookeeperAddress;

	private ZooKeeperClient zooKeeperClient;

	public String getZookeeperAddress() {
		return zookeeperAddress;
	}

	public void setZookeeperAddress(String zookeeperAddress) {
		this.zookeeperAddress = zookeeperAddress;
	}

	@Override
	public ZooKeeperClient getObject() throws Exception {
		return zooKeeperClient;
	}

	@Override
	public Class<?> getObjectType() {
		return ZooKeeperClient.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Builder<InetSocketAddress> b = ImmutableList.builder();
		String address[] = zookeeperAddress.split(",");
		for (String ad : address) {
			InetSocketAddress ia = NetUtil.toAddress(ad);
			b.add(ia);
		}
		List<InetSocketAddress> zooKeeperServers = b.build();
		this.zooKeeperClient = new ZooKeeperClient(Amount.of(10000, Time.MILLISECONDS), zooKeeperServers);
	}

}
